import React, { Component } from 'react'
import { Table,Button,Switch,Modal,Form,Input ,Select} from 'antd';
import { FormOutlined,DeleteOutlined,LeftSquareOutlined } from '@ant-design/icons';
import axios from "axios"
import style from "./users.module.css"
const { Option } = Select;


export default class Admin extends Component {
    state={
        // 存放请求数据
        dataList:[],

        // 显示隐藏添加弹框
        visible:false,

        // 显示隐藏更新弹框
        visibleAction:false,

        //当前更新的这一项
          current:{},       

        // 表格每一列
         columns: [
            {
              title: '角色名称',
              dataIndex: 'roleName',
              key: 'roleName',
              render: text => <b>{text}</b>,
            },
            {
              title: '管理员名',
              dataIndex: 'username',   
              key: 'username',   
            },
            {
              title: '管理员状态',
              dataIndex: 'roleState',   
              key: 'roleState',  
              render:(text,item)=>{
                  return <div>
                      <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked={text} disabled={item.default} onChange={()=>{this.switchFn(item)}}/>
                  </div>
              }
            },
          
            {
              title: '管理员操作',
              key: 'action',
              render: (text) => {
                  return <div>
                       <Button type="primary" shape="circle" icon={<FormOutlined />} onClick={()=>{this.actionFn(text)}} className={style.actionbtn}  disabled={text.default} />
                       <Button type="danger" shape="circle" icon={<DeleteOutlined />}  onClick={()=>{this.delFn(text)}}  disabled={text.default} />
                  </div>
              }
            },
          ]
    }

    componentDidMount() {
        axios.get("http://localhost:5000/administrators").then(res=>{
            this.setState({
                dataList:res.data
            })
        })
    }

    //点击ok添加
    handleOk = () => {
      // 将表单数据添加到后台以及页面
      this.refs.myform.validateFields().then(res=>{
        //  console.log(res)
         let arr = ["管理员","超级管理员"]
          axios.post(`http://localhost:5000/administrators`,{
          ...res,
          "roleState": false,
          "default": false,
          "roleType":  arr.indexOf(res.roleName)+1
        }).then(res=>{
          // console.log(res.data)
          this.setState({
            dataList:[...this.state.dataList,res.data],
            visible: false
          })
        })
      })

      setTimeout(()=>{
        this.refs.myform.resetFields()
      })
      
    };
  

    // 点击取消
    handleCancel =() => {
      this.setState({
        visible: false,
      });
      this.refs.myform.resetFields()
    };

    // 点击编辑显示弹框并显示对应数据
    actionFn(text){
      this.setState({
        visibleAction:true,
        current:text       //当前更新的这一项
      })
  
      setTimeout(()=>{
        this.refs.myformAction.setFieldsValue({
          username:text.username,
          password:text.password,
          roleName:text.roleName
        })
      },0)
    }


    //点击ok更新
    handleOkAction=()=>{
      this.refs.myformAction.validateFields().then(res=>{
        let arr = ["管理员","超级管理员"]
        // console.log(res) 只有表单的三个数据，缺少的id用current.id代替
        axios.put(`http://localhost:5000/administrators/${this.state.current.id}`,{
          ...this.state.current,
          ...res,
          "roleType": arr.indexOf(res.roleName)+1
        }).then(res=>{

          this.setState({
            dataList:this.state.dataList.map(item=>{
                if(item.id===this.state.current.id){
                    return res.data
                }else{
                    return item
                }
            }),
              visibleAction:false
            })
        })
      })
    }


    // 点击更新取消
    handleCancelAction=()=>{
      this.setState({
        visibleAction:false
      })
    }


    // 点击删除
    delFn(text){
      axios.delete(`http://localhost:5000/administrators/${text.id}`).then(res=>{
        this.setState({
          dataList:this.state.dataList.filter(item=>item.id !== text.id)
        })
      })
    }


    // 点击选择器
      switchFn(item){
      this.setState({
          dataList:this.state.dataList.map(data=>{
              if(data.id===item.id){
                  return {
                      ...data,
                      roleState:!data.roleState
                  }
              }else{
                  return data
              }
          }
      )
      })
      axios.put(`http://localhost:5000/administrators/${item.id}`,{
          ...item,
          roleState:!item.roleState
      }).then(res=>{
          // console.log(res)
      })
  }


    render() {
        return (
            <div>
              
                <div>
                  <Button className={style.btn} type="primary" size="large" onClick={()=>{
                        this.setState({
                          visible: true,
                        });
                  }}>添加管理员</Button>

                    <span className={style.ic} onClick={()=>{
                        this.props.history.push("/user-manage/users")
                    }}><LeftSquareOutlined /></span>

                </div>


                {/* 添加弹出框 */}
                <Modal
                  title="添加管理员"
                  visible={this.state.visible}
                  onOk={this.handleOk}
                  onCancel={this.handleCancel}
                  bodyStyle={{background:"rgba(214,213,183,0.1)"}}
                >
                    <Form
                      ref="myform"
                      layout="vertical"
                      name="form_in_modal"
              
                    >
                        <Form.Item
                          name="username"
                          label="管理员名"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >
                          <Input />
                        </Form.Item>

                        <Form.Item
                          name="password"
                          label="密码"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >
                          <Input />
                        </Form.Item>


                        <Form.Item
                          name="roleName"
                          label="角色名称"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >

                            <Select
                                showSearch
                                placeholder="请选择一个角色"
                            >
                                <Option value="超级管理员">超级管理员</Option>
                                <Option value="管理员">管理员</Option>
                            </Select>
                        
                        </Form.Item>
                    </Form>

                </Modal>


                  {/* 更新弹出框 */}
                  <Modal
                  title="更新管理员信息"
                  visible={this.state.visibleAction}
                  onOk={this.handleOkAction}
                  onCancel={this.handleCancelAction}
                  bodyStyle={{background:"rgba(214,213,183,0.1)"}}
                >
                    <Form
                      ref="myformAction"
                      layout="vertical"
                      name="form_in_modalAction"
              
                    >
                        <Form.Item
                          name="username"
                          label="管理员名"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >
                          <Input />
                        </Form.Item>

                        <Form.Item
                          name="password"
                          label="密码"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >
                          <Input />
                        </Form.Item>


                        <Form.Item
                          name="roleName"
                          label="角色名称"
                          rules={[{ required: true, message: 'Please input the title of collection!' }]}
                        >

                            <Select
                                showSearch
                                placeholder="请选择一个角色"
                            >
                                <Option value="超级管理员">超级管理员</Option>
                                <Option value="管理员">管理员</Option>
                            </Select>
                        
                        </Form.Item>
                    </Form>

                </Modal>


                <Table columns={this.state.columns}
                 dataSource={this.state.dataList} 
                 rowKey={item=>item.id}   //每行加key值属性
                 Pagination ={{                    //每页显示条数属性
                   pageSize:5    
               }}
                 />


            </div>
        )
    }
}
